/**
 * 
 */
package com.lmm.test.generate;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;

/**
 * @author leiming
 *
 */
public class GenerateDiagnosisSql {
	//对应文件
	private static final String FILE_NAME="prarams.txt";
	//接口id
	private static final int INTERFACES_ID=36;
	private static final String SQL_PREFIX = "INSERT INTO cfg_interface_url_params (id, url_id, param_name, param_value, description, sort) VALUES (";
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		InputStream in = GenerateDiagnosisSql.class.getResourceAsStream(FILE_NAME);
		//List<String> lines = FileUtils.readLines(file, "utf-8");
		List<String> lines = null;
		try {
			 lines = IOUtils.readLines(in, "utf-8");
			 String sql = generateSql(lines, 180);
			 System.out.println(sql);
		 } finally {
				IOUtils.closeQuietly(in);
		}
	}

	private static String generateSql(List<String> lines,int startRow){
		StringBuilder sb = new StringBuilder();
		int sort =0;
		for(String line:lines){
			if("".equals(line.trim())){
				continue;
			}
			String name = getFieldName(line);
			String value = getFieldValue(line);
			String comment  = getFieldComment(line);
			sb.append(generateLineSql(startRow++, name, value, comment, sort++)+"\n");
		}
		return sb.toString();
	}
	
	/**
	 * 生成行sql
	 * @param row
	 * @param name
	 * @param value
	 * @param comment
	 * @param sort
	 * @return
	 */
	private static String generateLineSql(int row,String name,String value,String comment,int sort){
		StringBuilder sb = new StringBuilder(SQL_PREFIX);
		sb.append(row);
		sb.append(","+INTERFACES_ID);
		sb.append(",'"+name+"'");
		sb.append(",'"+value+"'");
		if(comment==null){
			sb.append(",null");
		}else{
			sb.append(",'"+comment+"'");
		}
		
		sb.append(","+sort+");");
		return sb.toString();
	} 
	
	/**
	 * 获取字段名称
	 * @param line
	 * @return
	 */
	private static  String getFieldName(String line){
		String t[] = line.split("-");
		if(t.length<1){
			throw new IllegalArgumentException("line 参数不对");
		}
		String name = t[0];
		//将首字母转换为小写
		if(Character.isUpperCase(name.charAt(0))){
			 return (new StringBuilder()).append(Character.toLowerCase(name.charAt(0))).append(name.substring(1)).toString().trim();
		}
		return t[0].trim();
	}
	/**
	 * 获取字段名称
	 * @param line
	 * @return
	 */
	private static  String getFieldValue(String line){
		String t[] = line.split("-");
		if(t.length<2){
			return "";
		}
		return t[1].trim();
	}
	/**
	 * 获取字段名称
	 * @param line
	 * @return
	 */
	private static  String getFieldComment(String line){
		String t[] = line.split("-");
		if(t.length<3){
			return null;
		}
		return t[2].trim();
	}
}
